import 'package:dio/dio.dart';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import '../../base/Constant.dart';
import '../../util/BlankToolBarTool.dart';
import 'CardListPage.dart';
import '../../util/AppSaveInfoUtil.dart';
import '../../util/LoadingUtil.dart';
import '../../http/Api.dart';
import '../../http/HttpUtil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import '../../base/application.dart';
import '../../entity/CardEntity.dart';
import '../../util/SignUtil.dart';

class TXPage extends StatefulWidget {
  TXPage({Key key}) : super(key: key);

  @override
  _TXPageState createState() => _TXPageState();
}

class _TXPageState extends State<TXPage> {
  BlankToolBarModel barModel = BlankToolBarModel();
  String account = '';
  String token = "";
  String card_id = '';
  String bank_name = '';
  String truename = '';
  String account_type = '';
  String balance = "0";
  final _moneyController = TextEditingController(); //

  @override
  void initState() {
    super.initState();
    // print(APPLIC.map);
    getString(TOKEN).then((value) {
      setState(() {
        token = value;
        getUserInfo();
        loadList();
      });
    });
  }

  loadList() async {
    FormData formData = new FormData.fromMap({
      "token": token,
    });
    Response<String> response =
        await HttpUtil().post(Api.URL_BANKCARD_LIST, data: formData);
    Map userMap = json.decode(response.data);
    if (userMap['code'] == 1 && mounted) {
      if ((userMap['data']['list'] as List).length == 0) {
        Fluttertoast.showToast(msg: "请先添加银行卡");
        Navigator.of(context)
            .pushReplacement(MaterialPageRoute(builder: (context) {
          return new CardListPage();
        }));
        return;
      }
      CardEntity data = (userMap['data']['list'] as List)[0];
      bank_name = data.bank_name;
      card_id = data.id;
      account = data.account;
      account_type = data.bank_id;
      truename = data.truename;
      setState(() {});
    }
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: new AppBar(
          title: new Text(
            "提现",
            style: TextStyle(
                fontSize: ScreenUtil.getInstance().setSp(BIG_FONT_SIZE),
                color: Colors.black),
          ),
          elevation: 0.5,
          backgroundColor: Colors.white,
          brightness: Brightness.light,
          centerTitle: true,
          iconTheme: new IconThemeData(color: Colors.black),
        ),
        body: BlankToolBarTool.blankToolBarWidget(context,
            model: barModel,
            body: Container(
                child: Column(children: <Widget>[
              Expanded(
                  child: new SingleChildScrollView(
                      scrollDirection: Axis.vertical,
                      physics: BouncingScrollPhysics(),
                      child: new Column(children: <Widget>[
                        // Container(
                        //   padding: EdgeInsets.all(
                        //       ScreenUtil.getInstance().setHeight(DP_20)),
                        //   margin: EdgeInsets.fromLTRB(0,
                        //       ScreenUtil.getInstance().setHeight(DP_20), 0, 0),
                        //   color: Colors.white,
                        //   child: new GestureDetector(
                        //     onTap: () {
                        //       Navigator.of(context).push(
                        //           new MaterialPageRoute(builder: (context) {
                        //         return new CardListPage(
                        //           type: '1',
                        //         );
                        //       }));
                        //     },
                        //     child: new Row(
                        //       children: <Widget>[
                        //         Text('  '),
                        //         // Expanded(
                        //         //   child: Text(
                        //         //     '提现',
                        //         //     style: TextStyle(
                        //         //         fontSize: ScreenUtil.getInstance()
                        //         //             .setSp(SMALL_FONT_SIZE),
                        //         //         color: Colors.black87),
                        //         //   ),
                        //         // ),
                        //         // Expanded(
                        //         //   child: Text(
                        //         //     'ces',
                        //         //     style: TextStyle(
                        //         //         fontSize: ScreenUtil.getInstance()
                        //         //             .setSp(SMALL_FONT_SIZE),
                        //         //         color: Colors.black87),
                        //         //   ),
                        //         // ),
                        //       ],
                        //     ),
                        //   ),
                        // ),
                        Container(
                          padding: EdgeInsets.all(
                              ScreenUtil.getInstance().setHeight(DP_20)),
                          margin: EdgeInsets.fromLTRB(0,
                              ScreenUtil.getInstance().setHeight(DP_20), 0, 0),
                          color: Colors.white,
                          child: new GestureDetector(
                            onTap: () {
                              Navigator.of(context).push<CardEntity>(
                                  new MaterialPageRoute(builder: (context) {
                                return new CardListPage(
                                  type: '1',
                                );
                              })).then((CardEntity data) {
                                if (data == null) {
                                  return;
                                }
                                setState(() {
                                  bank_name = data.bank_name;
                                  card_id = data.id;
                                  account = data.account;
                                  account_type = data.bank_id;
                                  truename = data.truename;
                                });
                              });
                            },
                            child: new Row(
                              children: <Widget>[
                                Text('  '),
                                Expanded(
                                  child: Text(
                                    '提现至',
                                    style: TextStyle(
                                        fontSize: ScreenUtil.getInstance()
                                            .setSp(SMALL_FONT_SIZE),
                                        color: Colors.black87),
                                  ),
                                ),
                                Expanded(
                                  child: Text(
                                    bank_name == null || bank_name == ''
                                        ? ''
                                        : (bank_name + '(' + account + ')'),
                                    style: TextStyle(
                                        fontSize: ScreenUtil.getInstance()
                                            .setSp(SMALL_FONT_SIZE),
                                        color: Colors.black87),
                                  ),
                                ),
                                Icon(
                                  Icons.arrow_forward_ios,
                                  color: Colors.black87,
                                  size: 20,
                                )
                              ],
                            ),
                          ),
                        ),
                        Container(
                            padding: EdgeInsets.all(
                                ScreenUtil.getInstance().setHeight(DP_20)),
                            margin: EdgeInsets.fromLTRB(
                                0,
                                ScreenUtil.getInstance().setHeight(DP_20),
                                0,
                                0),
                            color: Colors.white,
                            child: new Column(
                              children: <Widget>[
                                new Row(
                                  children: <Widget>[
                                    Text('  '),
                                    Expanded(
                                      child: Text(
                                        '提现金额',
                                        style: TextStyle(
                                            fontSize: ScreenUtil.getInstance()
                                                .setSp(SMALL_FONT_SIZE),
                                            color: Colors.black87),
                                      ),
                                    ),
                                  ],
                                ),
                                new Row(
                                  children: <Widget>[
                                    Text('  '),
                                    Text('¥'),
                                    Expanded(
                                      child: new TextField(
                                        // focusNode: _contentFocusNode,
                                        controller: _moneyController,
                                        keyboardType: TextInputType.phone,
                                        decoration: new InputDecoration(
                                            border: InputBorder.none,
                                            hintText: '请输入提现金额'),
                                      ),
                                    ),
                                  ],
                                ),
                                Divider(
                                  height: 1,
                                ),
                                new Row(
                                  children: <Widget>[
                                    Text('  '),
                                    Text('账户余额：'),
                                    Expanded(
                                      child: Text(balance),
                                    ),
                                    GestureDetector(
                                      onTap: () {
                                        _moneyController.text = balance;
                                      },
                                      child: Text('全部提现'),
                                    )
                                  ],
                                ),
                              ],
                            )),
                        new Container(
                          width: double.infinity,
                          height: ScreenUtil.getInstance().setHeight(DP_70),
                          margin: EdgeInsets.fromLTRB(50, 30, 50, 0),
                          decoration: new BoxDecoration(
                              color: mainColor,
                              borderRadius: BorderRadius.circular(20.0)),
                          padding: EdgeInsets.fromLTRB(0.0, 0.0, 0.0, 0.0),
                          child: new FlatButton(
                            child: new Padding(
                              padding: EdgeInsets.all(0.0),
                              child: new Text(
                                '确认提现（预计两小时内到账）',
                                style: new TextStyle(
                                    color: Colors.white,
                                    fontSize:
                                        ScreenUtil.getInstance().setSp(23)),
                              ),
                            ),
                            onPressed: () {
                              submitFeed();
                            },
                          ),
                        )
                      ])))
            ]))));
  }

  void submitFeed() {
    //提示
    String msgStr = "";

    if (!_moneyController.text.isNotEmpty) {
      msgStr = "金额不能为空";
    }
    // if (!_nameController.text.isNotEmpty) {
    //   msgStr = "姓名不能为空";
    // }
    // if (bank_id == '' || bank_id == null) {
    //   msgStr = "请选择银行";
    // }
    if (bank_name == null || bank_name == '') {
      msgStr = "请选择提现至";
    }
    if (msgStr != '') {
      showDialog(
          context: context,
          builder: (context) {
            return new AlertDialog(
              title: new Text("提示信息"),
              content: new Text(msgStr),
              actions: <Widget>[
                new FlatButton(
                    child: new Text("确定"),
                    onPressed: () {
                      Navigator.of(context).pop();
                    }),
              ],
            );
          });
    } else {
      showDialog(
          context: context,
          barrierDismissible: false,
          builder: (_) {
            return new NetLoadingDialog(
              loadingText: '添加中...',
              bgColor: Color.fromARGB(255, 0, 0, 0),
              requestCallBack: null,
              outsideDismiss: false,
            );
          });
      add();
    }
  }

  add() async {
    FormData formData = new FormData.fromMap({
      "token": token,
      'account_type': account_type,
      'account': account,
      'money': _moneyController.text,
      'truename': truename
    });
    print(formData);
    Response<String> response =
        await HttpUtil().post(Api.URL_BALANCE_DRAW, data: formData);
    Navigator.of(context).pop(1);
    Map userMap = json.decode(response.data);
    print(userMap);
    int code = userMap["code"];
    String msg = userMap["msg"];
    Fluttertoast.showToast(msg: msg);
    if (code == 1) {
      Navigator.of(context).pop("1");
    }
    return true;
  }

  getUserInfo() async {
    Map map = new Map();
    map['token'] = token;
    map['sign_type'] = createSignType(Api.URL_USER_GETMSG);
    print(map);
    Response<String> response =
        await HttpUtil().post(Api.URL_USER_GETMSG, data: getSign(map));
    Map userMap = json.decode(response.data);
    print(userMap);
    if (userMap['code'] == 1 && mounted) {
      setState(() {
        APPLIC.userInfoMap = userMap['data'];
        userMap = userMap['data'];
        balance = userMap['user_msg']['balance'];
      });
    }
  }
}
